<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="author" content="lijinbo" />
    <title>使用js进行媒体查询</title>
    <style></style>
  </head>

  <body>
    <div class="box">
      <p>
        文章参考：
        <a href="https://blog.csdn.net/weixin_46267040/article/details/125369790" target="_blank">
          JavaScript 媒体查询
        </a>
      </p>
    </div>
    <hr />
    <ul id="one"></ul>

    <script>
      // 方案一：监听屏幕变化
      window.addEventListener('resize', () => {
        const w = window.innerWidth
        console.log(w)
        if (w < 1024) {
          const one = document.getElementById('one')
          const li = document.createElement('li')
          li.innerHTML = w
          one.append(li)
        }
      })
      // 方案二：使用 matchMedia 进行媒体查询
      const mql = window.matchMedia('(max-width: 767px)')
      if (mql.matches) {
        console.log('匹配成功', mql.matches)
      } else {
        console.log('匹配失败', mql.matches)
      }

      // window.matchMedia 的语法类似于 css 的 @media
      // 常用的屏幕匹配参数
      const screenMatches = {
        // 手机
        xs: matchMedia('(max-width: 767px)').matches,
        // 平板
        sm: matchMedia('(min-width: 768px) and (max-width: 991px)').matches,
        // pc
        lg: matchMedia('(min-width: 1200px) and (max-width: 1919px)').matches
      }
      console.log(screenMatches)
    </script>
  </body>
</html>
